package com.zys.el.time.ws.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zys.el.time.constants.MQConstants;
import com.zys.el.time.ws.dto.ChatDTO;
import com.zys.el.time.ws.mapper.ChatMapper;
import com.zys.el.time.ws.model.Chat;
import com.zys.el.time.ws.service.IChatService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;


@Service
public class ChatService extends ServiceImpl<ChatMapper, Chat>
        implements IChatService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void saveInDB(JSONObject msgData) {
        Chat chat = new Chat();
        // 目前只存文字
        chat.setRoomId(msgData.getLong("roomId"));
        chat.setContent(msgData.getString("msg"));
        chat.setSenderId(msgData.getLong("fromUserId"));
        chat.setType(1);
        chat.setCreateTime(msgData.getObject("createTime", LocalDateTime.class));
        this.save(chat);
    }


    @Override
    public Boolean save(String key, JSONObject msgData) {
        // 保存至redis
        msgData.put("createTime", LocalDateTime.now().toString()); // 存入发送时间
        Boolean b = stringRedisTemplate.opsForZSet().add(key, msgData.toString(), System.currentTimeMillis());
        // 存入消息队列(做入库操作)
        rabbitTemplate.convertAndSend(MQConstants.SAVE_CHAT_KEY, msgData);

        // 返回
        return b;
    }
}




